<template>
  <div class="app-declare-container">
    <nu-col :span="24" style="width:100%;height:100%">
      <nu-row class="row" :gutter="20" ref="formData">
        <nu-col :span="24" class="col">
          <nu-button type="primary" class="searchButton" @click="addTable">新增</nu-button>
        </nu-col>
        <nu-col :span="24">
          <div class="line"></div>
        </nu-col>
      </nu-row>
      <NuTableList :showFilter="false" :columns="columns" :dataSource="dataSource" :options="options"
        :operates="operates(this)" :pagination="pagination" @handleSizeChange="handleSizeChange"
        @handleChangePage="handleChangePage" @handleCurrentChange="handleCurrentChange" style="margin: 0 0 20px 0">
      </NuTableList>
    </nu-col>
    <!-- </nu-row> -->
    <nu-dialog :title="dialogTitle" :visible.sync="dialogShow" width="40%" center :close-on-click-modal="false" top="5vh"
      :modal-append-to-body="false" @close="diaClose">
      <div class="dialogHeaderSearch">
        <NuVerifyForm :model="dialogFormData" ref="dialogFormData" label-width="160px" class="submitForm"
          @submitForm="diaSubmitForm" :buttons="fyButtons">
          <NuformItem label="调峰指令出力（MW）" prop="deepPeakCommandOutput" width="70%"
            :rules="[{ required: true, message: '调峰指令出力不能为空' }]">
            <nu-input type="text" v-model="dialogFormData.deepPeakCommandOutput" size="middle"></nu-input>
          </NuformItem>

          <NuformItem label="调峰时间范围" prop="time" width="70%" :rules="[{ required: true, message: '时间不能为空' }]">
            <!-- <el-date-picker
              v-model="dialogFormData.time"
              type="datetimerange"
              placeholder="请选择日期"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%"
              format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
            >
            </el-date-picker> -->
            <nu-datepickerLocal placeholder="请选择调峰时间范围" v-model="dialogFormData.time" format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%" range-separator="至" :minuteInterval="5" />
            <!-- <nu-datepickerLocal placeholder="请选择调峰时间范围" v-model="dialogFormData.time" format="HH:mm" style="width: 100%"
              range-separator="至" :minuteInterval="5" dateType="hours" :showButtons="true" /> -->
          </NuformItem>
          <NuformItem label="调峰机组" prop="bidUnitId" width="70%" :rules="[
            { required: true, message: '调峰机组不能为空' },
          ]">
            <!-- <el-select class="searchSelect"  :="bidUnitIdList" :filterable="true"  type="text" :valueName="'phyunitId'" :allow-create="true"  default-first-option
                :label="'phyunitName'" v-model="dialogFormData.bidUnitId"
              autocomplete="off" style="width: calc(100% - 5px); margin-left: 2px">
            </el-select> -->
            <el-select v-model="dialogFormData.bidUnitId" multiple filterable allow-create default-first-option
              style="width:100%" placeholder="请选择调峰机组">
              <el-option v-for="item in bidUnitIdList" :key="item.value" :label="item.phyunitName"
                :value="item.phyunitId">
              </el-option>
            </el-select>
          </NuformItem>
          <NuformItem label="调峰实际出力（MW）" prop="deepPeakActualOutput" width="70%" :rules="[
            { required: true, message: '调峰实际出力不能为空' },
          ]">
            <nu-input type="text" v-model="dialogFormData.deepPeakActualOutput" size="middle"></nu-input>
          </NuformItem>
          <!-- <NuformItem label="有偿调峰考核系数" prop="checkCoeff" width="70%" :rules="[
            { required: true, message: '有偿调峰考核系数不能为空' },
          ]">
              <nu-input type="number" v-model="dialogFormData.checkCoeff" size="middle"></nu-input>
          </NuformItem> -->
        </NuVerifyForm>
        <nu-button class="dialogSearchButton" type="primary" @click="diaClose">取消</nu-button>
        <nu-button class="dialogSearchButton" type="primary" @click="diaSave">确定</nu-button>

      </div>
    </nu-dialog>
  </div>
</template>
<script>
import nuCol from "@/components/base/col.vue";
import nutbTitle from "@/components/base/tableTitle.vue";
import NuVerifyForm from "@/components/verify-form";
import NuformItem from "@/components/verify-form/form-item.vue";
import nuInput from "@/components/base/input";
import nuSelect from "@/components/base/select";
import nuButton from "@/components/base/button";
import NuTableList from "@/components/tableList/TableFormList";
import nuRow from "@/components/base/row.vue";
import nuDialog from "@/components/base/dialog";
import nuDatepickerLocal from "@/components/DatepickerLocal/VueDatepickerLocal";
import { getDateTime, replaceDateTime } from "@/utils/ruoyi";
const operates = (that) => [
  {
    label: "修改",
    icon: "",
    width: "50px",
    isShow: (row) => {
      return true;
    },
    disabled: (row) => {
      return false;
    },
    method: (row) => {
      that.openEdit(row);
    },
  },
  {
    label: "删除",
    icon: "",
    width: "50px",
    isShow: (row) => {
      return true;
    },
    disabled: (row) => {
      return false;
    },
    method: (row) => {
      that.deleteRow(row);
    },
  },


];
export default {
  name: "declare",
  components: {
    nuCol,
    nutbTitle,
    NuVerifyForm,
    NuformItem,
    nuInput,
    nuSelect,
    nuButton,
    NuTableList,
    nuRow,
    nuDialog,
    nuDatepickerLocal
  },
  data() {
    return {
      operates,
      currentRow: null,
      dataSource: [],
      columns: [
        {
          label: "序号",
          prop: "index",
          width: "70px",
          render: (h, params) => {
            return h("span", params.index + 1);
            // return h('span', params.index + 1 + (this.pagination.pageNum - 1) * this.pagination.pageSize);
          },
        },
        {
          label: "调峰指令出力（MW）",
          prop: "deepPeakCommandOutput",
        },
        {
          label: "调峰机组",
          prop: "bidUnitId",
          render: (h, params) => {
            // let arr = []
            // if (params.row.bidUnitId) {
            //   params.row.bidUnitId.split(",").map((value) => {
            //     this.bidUnitIdList.map((res) => {
            //       if (res.phyunitId == value) {
            //         arr.push(res.phyunitName)
            //       }
            //     })
            //   })
            // }
            return h('span', params.row.bidUnitName);
          },
        },
        {
          label: "调峰实际出力（MW）",
          prop: "deepPeakActualOutput",

        },
        // {
        //   label: "有偿调峰考核系数",
        //   prop: "checkCoeff",
        // },
        {
          label: "调峰时间范围",
          prop: "upperLimit",
          width: "300px",
          render: (h, params) => {
            if (params.row.deepPeakStartDate && params.row.deepPeakEndDate && params.row.deepPeakStartTime && params.row.deepPeakEndTime) {
              return h("span", replaceDateTime(params.row.deepPeakStartDate, 'day') + ' '
                + replaceDateTime(params.row.deepPeakStartTime, 'time') + " - "
                + replaceDateTime(params.row.deepPeakEndDate, 'day') + ' '
                + replaceDateTime(params.row.deepPeakEndTime, 'time'));
            } else {
              return ''
            }
          },
        },
        {
          label: "记录维护时间",
          prop: "updateDate",
        },
        {
          label: "维护人",
          prop: "updateBy",
        },
      ],
      bidUnitIdList: [],
      options: {
        "default-expand-all": true,
        "element-loading-background": "rgba(225,239,242)",
        "element-loading-text": "数据正在加载中",
        "row-key": "pid",
        "header-cell-style": {
          background: "rgba(105, 159, 209, 0.7)",
          color: "#fff",
          fontWeight: "bold",
          fontsize: "16px",
        },
        height: "calc(100vh - 320px)",
      },
      dialogTitle: "",
      dialogShow: false,
      dialogFormData: {
        time: [],
        bidUnitId: [],// 多个机组ID，用,分隔
        deepPeakCommandOutput: "",
        deepPeakActualOutput: "",
        deepPeakStartDate: "",
        deepPeakEndDate: "",
        // checkCoeff: ""
      },
      nameList: [{ label: "机组1", value: 1 }, { label: "机组2", value: 2 }],
      typeList: [
        { label: "日前申报", value: 1 },
        { label: "临时申报", value: 2 },
      ],
      fyButtons: [],
      pagination: {
        pageSize: 20,
        total: 0,
        pageNum: 1,
      },
    };
  },
  mounted() {
    this.getDeclareData();
    this.getCrewManageTableData()
    this.dialogFormData.time = [getDateTime('hours') + ':00', getDateTime('hours') + ':00']
  },
  methods: {
    /**
     * 获取表格数据
     */
    getDeclareData() {
      // let postData = {};
      // for (let k in postData.query) {
      //   if (
      //     postData.query[k] &&
      //     Object.prototype.toString.call(postData.query[k]) == "[object String]"
      //   ) {
      //     postData.query[k] = postData.query[k].toString().trim();
      //   }
      // }
      this.$httpGet(window.api.peakList, this.pagination)
        .then((res) => {
          if (res.code) {
            // console.log(res.data)
            this.dataSource = res.rows;
            this.pagination.total = res.total;
          } else {
            this.dataSource = [];
          }
        })
        .catch((err) => {
          this.dataSource = [];
        });
    },

    // 获取机组
    getCrewManageTableData() {
      let postData = {
        pageSize: 99999,
        total: 0,
        pageNum: 1,
        phyunitName: ""
      };
      for (let k in postData.query) {
        if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.$httpGet(window.api.getCrewManageTableData, postData).then(res => {
        if (res.code == 200 && res.rows) {
          this.bidUnitIdList = res.rows
        } else {
        }
      }).catch(err => {

      });
    },
    /**
     * 新增
     */
    addTable() {
      this.dialogTitle = "新增";
      this.dialogShow = true;
    },
    /**
     * form组件内置查询事件
     */
    searchForm(val) {
      if (val) {
        this.getDeclareData();
      }
    },
    /**
     * 弹窗-保存
     */
    diaSave() {
      this.$refs["dialogFormData"].submitForm("form");
    },
    /**
     * 修改 接口
     */
    peakEdit() {
      let postData = {
        ...this.dialogFormData,
      };
      if (postData.bidUnitId instanceof Array) {
        postData.bidUnitId = postData.bidUnitId.join()
      }
      let st = getDateTime('obj', this.dialogFormData.time[0])
      let et = getDateTime('obj', this.dialogFormData.time[1])

      postData.deepPeakStartDate = getDateTime('day', this.dialogFormData.time[0], false)
      postData.deepPeakEndDate = getDateTime('day', this.dialogFormData.time[1], false)
      postData.deepPeakStartTime = st.curHours + st.curMinutes + st.curSeconds
      postData.deepPeakEndTime = et.curHours + et.curMinutes + et.curSeconds
      // delete postData.time
      console.log(st,et)
      if (postData.relatedDevId == postData.relatedDevName) {
        postData.relatedDevId == postData.oldRelatedDevId;
      }
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.$httpPut(window.api.peakEdit, postData)
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: res.msg,
              type: "success",
            });
            this.diaClose();
            this.getDeclareData();
          } else {
          }
        })
        .catch((err) => { });
    },
    /**
     * 弹窗-关闭
     */
    diaClose() {
      this.dialogShow = false;
      this.resetForm("dialogFormData");
      this.dialogFormData.time = [getDateTime('hours') + ':00', getDateTime('hours') + ':00']
    },
    /**
     * 重置表单
     */
    resetForm(formName) {
      this.$refs[formName].resetForm("form");
      for (let k in this[formName]) {
        this[formName][k] = "";
      }
    },
    /**
     * 每页条数变化事件
     */
    handleSizeChange(val) {
      this.pagination.pageNum = 1;
      this.pagination.pageSize = val;
      this.getDeclareData();
    },
    /**
     * 改变分页触发事件
     */
    handleChangePage(val) {
      this.pagination.pageNum = val;
      this.getDeclareData();
    },
    /**
     * 单选
     */
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    /**
     * dialogFormData组件内置提交事件
     */
    diaSubmitForm(val) {
      if (val) {
        if (this.dialogTitle == "修改") {
          this.peakEdit()
        } else if (this.dialogTitle == "新增") {
          this.peakAddRow()
        }
      }
    },

    peakAddRow() {
      let postData = {
        ...this.dialogFormData,
      };
      postData.bidUnitId = postData.bidUnitId.join()
      let st = getDateTime('obj', this.dialogFormData.time[0])
      let et = getDateTime('obj', this.dialogFormData.time[1])
      postData.deepPeakStartDate = getDateTime('day', this.dialogFormData.time[0], false)
      postData.deepPeakEndDate = getDateTime('day', this.dialogFormData.time[1], false)
      postData.deepPeakStartTime = st.curHours + st.curMinutes + st.curSeconds
      postData.deepPeakEndTime = et.curHours + et.curMinutes + et.curSeconds
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      delete postData.time
      this.$httpPost(window.api.peakAdd, postData)
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.diaClose();
            this.getDeclareData();
          } else {
            this.$message({
              message: "添加失败",
              type: "info",
            });
          }
        })
        .catch((err) => { });
    },
    /**
     * 表格-修改
     */
    openEdit(row) {
      this.dialogTitle = "修改";
      this.dialogShow = true;
      if (row.bidUnitId instanceof Array) {

      } else {
        row.bidUnitId = row.bidUnitId.split(",")
      }
      row.time = [replaceDateTime(row.deepPeakStartDate, 'day') + ' ' + replaceDateTime(row.deepPeakStartTime, 'time'), replaceDateTime(row.deepPeakEndDate, 'day') + ' ' + replaceDateTime(row.deepPeakEndTime, 'time')]
      Object.assign(this.dialogFormData, row);
    },

    // 删除一行
    deleteRow(row) {
      this.$confirm("确定要删除吗？", "确认删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.delDeepPeakCommandOutput(row);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    delDeepPeakCommandOutput(row) {
      this.$httpDel(window.api.peakRemove, row.id)
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getDeclareData();
          } else {
          }
        })
        .catch((err) => { });
    },
  },
};
</script>
<style scoped>
.app-declare-container {
  height: calc(100vh - 70px);
}

.hint {
  display: block;
  font-size: 14px;
  line-height: 28px;
  color: rgba(79, 84, 112, 1);
}

.dialogHeaderSearch {
  background-color: var(--model-bgc);
  padding: 10px;
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  justify-content: right;
}

.el-col {
  margin: 0;
}

.row {
  margin-left: 0 !important;
  margin-right: 0 !important;
}

.col {
  padding: 0px 10px 0px 10px;
}

.submitForm {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

::v-deep .el-form-item {
  margin: 20px 0 0 0;
}
</style>
